(function (w) {
    if (typeof jQuery == "undefined") {
        alert('jQuery is not imported.');
    }

    w.apiMenu = {};
    w.apiForm = {};

    const model = '/api/';
    const initApi = model + 'docs/init';

    let tmpMenu = '<div class="menu">\n' +
        '                <div class="menu-title p-y-1">{name}</div>\n' +
        '                <div class="menu-list hidden">\n' +
        '                    {menuItem}' +
        '                </div>\n' +
        '            </div>';
    let tmpMenuItem = '<div class="menu-item p-y-1" data-tag="{tag}">{name}</div>';

    function init() {
        let str = '';
        for (let menu of apiMenu) {
            let itemStr = '';
            for (let item of menu.method) {
                let itemName = item.comment;
                if (item.auth) {
                    itemName += '<span class="no-auth">免登录</span>';
                }
                if (item.permission) {
                    itemName += '<span class="no-perm">免鉴权</span>';
                }

                itemStr += tmpMenuItem.replace('{tag}', menu.name + '/' + item.name)
                    .replace('{name}', itemName);
            }
            str += tmpMenu.replace('{name}', menu.comment)
                .replace('{menuItem}', itemStr);
        }

        $('.aside-body').append(str);
    }

    let tmpInput = '<div class="flex p-y-1">\n' +
        '        <label class="label flex" for="{name}">{labelRequired}{label}：</label>\n' +
        '        <div class="form-item flex-grow">\n' +
        '            <input type="text" id="{name}" name="{name}" {isRequired} placeholder="{desc}"/>\n' +
        '        </div>\n' +
        '    </div>';
    let tmpInputNum = '<div class="flex p-y-1">\n' +
        '        <label class="label flex" for="{name}">{labelRequired}{label}：</label>\n' +
        '        <div class="form-item flex-grow">\n' +
        '            <input type="number" id="{name}" name="{name}" {isRequired} placeholder="{desc}"/>\n' +
        '        </div>\n' +
        '    </div>';
    let tmpRadio = '<div class="flex p-y-1">\n' +
        '        <label class="label flex">{labelRequired}{label}：</label>\n' +
        '        <div class="form-item flex flex-grow">\n' +
        '            <input type="radio" id="r1-{name}" name="{name}" {isRequired} value="1" placeholder="{desc}"/>\n' +
        '            <label for="r1-{name}">是</label>\n' +
        '            <input type="radio" id="r2-{name}" name="{name}" {isRequired} value="0" placeholder="{desc}"/>\n' +
        '            <label for="r2-{name}">否</label><span style="color: darkgray">({desc})</span>\n' +
        '        </div>\n' +
        '    </div>';
    let tmpTextarea = '<div class="flex p-y-1">\n' +
        '        <label class="label flex" for="{name}">{labelRequired}{label}：</label>\n' +
        '        <div class="form-item flex-grow">\n' +
        '            <textarea id="{name}" rows="3" name="{name}" {isRequired} placeholder="{desc}"></textarea>\n' +
        '        </div>\n' +
        '    </div>';

    function paramsDiv(name, type, required, desc = '') {
        let str = '';
        if (undefined === name || undefined === type || undefined === required) {
            return str;
        }

        if (undefined === desc || '' === desc) {
            desc = name;
        }

        let labelRequired = required ? '<span style="color: red;margin-right: 2px;">*</span>' : ''
        let isRequired = required ? 'required' : ''
        switch (type) {
            case 'int':
                str += tmpInputNum.replace('{label}', name)
                    .replaceAll('{labelRequired}', labelRequired)
                    .replaceAll('{isRequired}', isRequired)
                    .replaceAll('{desc}', desc)
                    .replaceAll('{name}', name);
                break;
            case 'string':
                str += tmpInput.replace('{label}', name)
                    .replaceAll('{labelRequired}', labelRequired)
                    .replaceAll('{isRequired}', isRequired)
                    .replaceAll('{desc}', desc)
                    .replaceAll('{name}', name);
                break;
            case 'bool':
                str += tmpRadio.replace('{label}', name)
                    .replaceAll('{labelRequired}', labelRequired)
                    .replaceAll('{isRequired}', isRequired)
                    .replaceAll('{desc}', desc)
                    .replaceAll('{name}', name);
                break;
            case 'json':
            case 'array':
                str += tmpTextarea.replace('{label}', name)
                    .replaceAll('{labelRequired}', labelRequired)
                    .replaceAll('{isRequired}', isRequired)
                    .replaceAll('{desc}', desc)
                    .replaceAll('{name}', name);
                break;
        }

        return str;
    }

    function copy(text) {
        if (undefined === text || '' === text) {
            return;
        }
        const input = document.createElement('textarea')
        input.value = text
        document.body.appendChild(input)
        input.select()
        input.setSelectionRange(0, input.value.length)
        const success = document.execCommand('copy')
        document.body.removeChild(input)
    }

    $(document).keyup(function (e) {
        'Enter' === e.key && $('.search').click();
    });

    $(document).ready(function () {
        const account = localStorage.getItem('account');
        $('.account').html(account);

        $.post(initApi, function (res) {
            if (res.code === 0) {
                w.apiMenu = res.data.menu;
                w.apiForm = res.data.form;
                init();
            }
        });
    });

    //菜单
    $(document).on('click', '.menu-title', function () {
        $(this).addClass('menu-click')
        $(this).next().removeClass('hidden')
        $('.menu-title').not(this).removeClass('menu-click').next().addClass('hidden')
    });

    //菜单项
    $(document).on('click', '.menu-item', function () {
        $(this).addClass('menu-item-click')
        $('.menu-item').not(this).removeClass('menu-item-click')
        let tag = $(this).data('tag')
        let formBodyItem = $('.form-body')
        formBodyItem.empty().append('<div class="form-body-breadcrumb" title="点击复制">' + model + tag + '</div>')
        $('.form-footer').removeClass('hidden')
        let params = apiForm[tag]
        if (undefined === params || '' === params) {
            return;
        }

        let str = '';
        for (let p of params) {
            //{name: 'ids', type: 'string', required: true, desc: 'ids'}
            str += paramsDiv(p.name, p.type, p.required, p.desc);
        }

        formBodyItem.append(str);
    });

    //表单提交
    $(document).on('click', '.search', function () {
        if (!form.checkValidity()) {
            return alert('有参数必填！');
        }

        let url = $('.form-body-breadcrumb').html();

        $.ajax({
            url: url,
            method: 'post',
            headers: {
                "token": localStorage.getItem('token')
            },
            data: $('.form').serializeArray(),
            success: function (res) {
                if ('' === res || undefined === res) {
                    return;
                }

                if ('object' === typeof res) {
                    $('.result').empty().append('<pre>' + JSON.stringify(res, undefined, 4) + '</pre>')
                } else {
                    $('.result').empty().append('<pre>' + res + '</pre>')
                }

                if (url.search('/Login/login') > 0) {
                    localStorage.setItem('account', res.data.account);
                    localStorage.setItem('token', res.data.token);
                    $('.account').html(res.data.account)
                } else if (url.search('/Login/logout') > 0 ||
                    -103 === res.code ||
                    -104 === res.code ||
                    -105 === res.code) {
                    localStorage.clear();
                    $('.account').html('')
                }
            },
            error: function (error) {
                console.log(error)
            }
        });
    });

    //复制
    $(document).on('click', '.form-body-breadcrumb', function () {
        copy($(this).html())
    });

    //刷新
    $(document).on('click', '.refresh', function () {
        window.location.reload()
    });

    //护眼
    $(document).on('click', '.eye', function () {
        $('body').toggleClass('green')
        let eyeItem = $('.eye')
        let eye = eyeItem.html()
        if ('护眼' === eye) {
            eyeItem.html('正常')
        } else {
            eyeItem.html('护眼')
        }
    });

})(window);